package own.stu.jobgib.playown.vediodown.bili.model.seasons;

import own.stu.jobgib.playown.vediodown.common.BaseModel;
import own.stu.jobgib.playown.vediodown.common.UrlUtil;
import own.stu.jobgib.playown.vediodown.common.model.BaseDataInfo;
import own.stu.jobgib.playown.vediodown.common.model.SimpleMediaItem;

import java.util.ArrayList;
import java.util.List;

@lombok.Data
public class SeasonArchive extends BaseModel<Data> implements BaseDataInfo<ArchivesItem, Page> {

    static String urlFormat = "https://api.bilibili.com/x/polymer/web-space/seasons_archives_list" +
            "?mid=%s&season_id=%s&sort_reverse=false&page_size=%d&page_num=%d";

    private UrlUtil.UrlEntity urlEntity;

    public static String getUrl(Long mid, Long seasonId, int pageSize) {
        return getUrl(mid, seasonId, pageSize, 1);
    }

    public static String getUrl(Long mid, Long seasonId, int pageSize, int pageNum) {
        return String.format(urlFormat, mid, seasonId, pageSize, pageNum);
    }

    public List<String> getExistUrls(String originUrl) {
        if (this.getData() == null) {
            logger.error("getItemList error: SeasonArchive is null");
            return new ArrayList<>();
        }

        return getExistUrls(this.getData().getPage(), originUrl);
    }

    public List<String> getExistUrls(Page pageInfo, String originUrl) {

        List<String> urls = new ArrayList<>();

        List<Integer> pageNumList = pageInfo.pageNumList();

        UrlUtil.UrlEntity urlEntity = UrlUtil.parse(originUrl);
        for (Integer pageNum : pageNumList) {
            urlEntity.getParams().put("page_num", pageNum + "");
            urls.add(UrlUtil.compose(urlEntity));
        }
        return urls;
    }

    @Override
    public List<ArchivesItem> getItemList() {

        if (this.getData() == null) {
            logger.error("getItemList error: SeasonArchive is null");
            return new ArrayList<>();
        }

        Data data = this.getData();
        return data.getArchives();
    }

    @Override
    public SimpleMediaItem transFor(ArchivesItem archivesItem) {
        SimpleMediaItem item = new SimpleMediaItem();

        item.setBvId(archivesItem.getBvid());
        item.setTitle(archivesItem.getTitle());
        item.setCover(archivesItem.getPic());
        long ctime = archivesItem.getCtime();
        if (ctime <= 10) {
            ctime *= 1000;
        }
        item.setDate(ctime);
        return item;
    }

    @Override
    public Long getUserId() {
        return (long) this.getData().getMeta().getMid();
    }
}
